<?php


namespace app\zmt\controller;


use app\zmt\model\bannerModel;
use cmf\controller\AdminBaseController;

class bannerController extends AdminBaseController
{
    public function index(){
        $banner = bannerModel::order('list_order','desc')->select();
        return $this->fetch('index',[
            'data' => $banner
        ]);
    }
    public function add(){
        return $this->fetch();
    }

    public function addpost(){
        $data = input();
        #$url = cmf_get_image_url($image);
        if(bannerModel::create($data)){
            $this->success('添加成功');
        }else{
            $this->error('添加失败');
        }
    }
    public function edit(){
        $id = input('id');
        $mobel = bannerModel::find($id);
        return $this->fetch('edit',[
            'banner' => $mobel,
        ]);
    }
    public function editPost(){
        if ($this->request->ispost()){
            $data = $this->request->post();
            if (!$data){
                $this->error('没有值，请重新修改');
            }
            $banner = bannerModel::find($data['id']);
            $banner->image = $data['image'];
            $banner->url   = $data['url'];
            if ($banner->save()){
                $this->success('修改成功');
            }else{
                $this->error('修改失败');
            }
        }else{
            $this->error('请用post提交');
        }
    }
    public function delete(){
        $id = input('id');
        if (bannerModel::destroy($id)){
            $this->success('删除成功');
        }else {
            $this->success('删除成功');
        }
    }

    public function order(){
        parent::listOrders(new BannerModel());
        $this->success('排序成功');
    }
    public function toggleSwitch()
    {
        $id = $this->request->param('id', 1, 'intval');
        $news = bannerModel::find($id);
        if ($news) {
            $news->switch = $news->switch ? 0 : 1;
            if ($news->save()) {
                return json(['status' => 1, 'msg' => '状态切换成功', 'switch' => $news->switch]);
            } else {
                return json(['status' => 0, 'msg' => '状态切换失败']);
            }
        } else {
            return json(['status' => 0, 'msg' => '新闻不存在']);
        }
    }
}